package com.jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwt.bean.User;

import java.util.Calendar;

public class JwtUtil {
    //key
    private static final String KEY = "adc123";
    //jackson操作对象
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 生成token
     * @param user
     * @return
     * @throws JsonProcessingException
     */
    public static String generateToken(User user)  {
        //new一个日期，设置过期时间
        Calendar time = Calendar.getInstance();
        time.add(Calendar.HOUR_OF_DAY,1);
        //claim:声明
        JWTCreator.Builder builder = null;
        String token = "";
        try {
            builder = JWT.create()
                    //payload的内容，由一个个的claim组成
                    .withClaim("userInfo",mapper.writeValueAsString(user))//user对象序列化为json字符串
                    .withExpiresAt(time.getTime());
            //最后一步签名，生成token
            token=builder.sign(Algorithm.HMAC256(KEY));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("java-jwt生成的token为："+token);
        return token;
    }

    /**
     * 校验token，成功返回token，失败返回null
     * @param tokenToBeVerify 要校验的token
     * @return
     */
    public static DecodedJWT verify(String tokenToBeVerify){
        DecodedJWT verify = null;
        try {
            //校验token
            verify=JWT.require(Algorithm.HMAC256(KEY)).build().verify(tokenToBeVerify);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            System.out.println("签名不一致");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            System.out.println("令牌过期");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            System.out.println("签名算法不匹配");
        }catch (InvalidClaimException e) {
            e.printStackTrace();
            System.out.println("payload不可用");
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("校验失败");
        }
        return verify;
    }

    /**
     * 解析json字符串成User对象
     * @param decodedJWT 符合规则的token
     * @param claimName 内容名
     * @return
     */
    public static User parse(DecodedJWT decodedJWT,String claimName){
        Claim claim = decodedJWT.getClaim(claimName);
        if (claim !=null) {
            String userJson = claim.asString();
            User user = null;
            try {
                //把userJson转换成User对象
                 user= mapper.readValue(userJson, User.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return user;
        }
        return null;
    }

}
